﻿using Abp.Runtime.Session;
using Abp.Timing;
using Hicap.QRCodeWarehouse.Core.Common;
using Hicap.QRCodeWarehouse.Core.EFCore;
using Hicap.QRCodeWarehouse.Core.Models.DbSet;
using Newtonsoft.Json;
using Serilog;

namespace Hicap.QRCodeWarehouse.Core.Managers
{
    public class GenerationRuleManager : ManagerBase<GenerationRule>, IGenerationRuleManager
    {
        public GenerationRuleManager(IUnitOfWork unitOfWork, IAbpSession session) : base(unitOfWork)
        {
            QueryCondition.Add(x => x.IsDeleted == false);

            int? companyId = session.GetCompanyId();
            if (companyId.HasValue) QueryCondition.Add(x => x.SubordinateCompanyId == companyId.Value);

            CreateActions.Add(x => x.CreatorUserId = session.UserId);
            CreateActions.Add(x => x.CreationTime = Clock.Now);
            UpdateActions.Add(x => x.LastModificationTime = Clock.Now);
            UpdateActions.Add(x => x.LastModifierUserId = session.UserId);
            DeleteActions.Add(x => x.DeletionTime = Clock.Now);
            DeleteActions.Add(x => x.DeleterUserId = session.UserId);
            DeleteActions.Add(x => x.IsDeleted = true);

            CreateCheckActions.Add(x =>
            {
                if (x.Id == 0) return true;
                Log.Warning($"GenerationRule CreateCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
            UpdateCheckActions.Add(x =>
            {
                if (x.Id > 0 && x.IsDeleted == false) return true;
                Log.Warning($"GenerationRule UpdateCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
            DeleteCheckActions.Add(x =>
            {
                if (x.IsDeleted == false) return true;
                Log.Warning($"GenerationRule DeleteCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
        }
    }
}